package cn.net.autocode.platform.table;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import cn.net.autocode.dbManager.Dao;
import cn.net.autocode.core.bean.ResultT;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/platform/tableRefAdd")
@RestController("AcTableRuleDetailTableRefAdd")
public class TableRefAdd {

    private final Dao dictDao;

    public TableRefAdd(@Qualifier("dictDao") Dao dictDao) {
        this.dictDao = dictDao;
    }

    @RequestMapping("load")
    public ResultT load(){
        return null;
    }

    @RequestMapping("queryPkFields")
    public ResultT queryPkFields(@RequestBody JSONObject param){
        JSONArray array = dictDao.queryJSONArray("select name value,name label,ac_table_fields.* from ac_table_fields where table_id=? order by name",param.getString("tableId"));
        return ResultT.success(array);
    }


    @RequestMapping("queryAcTables")
    public ResultT queryAcTables(){
        JSONArray array = dictDao.queryJSONArray("select table_name value,table_name label,ac_table.* from ac_table order by table_name");
        return ResultT.success(array);
    }

    @RequestMapping("queryFkFields")
    public ResultT queryFkFields(@RequestBody JSONObject param){
        JSONArray array = dictDao.queryJSONArray("select t1.name value,t1.name label,t1.* from ac_table_fields t1,ac_table t2 where t1.table_id=t2.id and t2.table_name=? " +
                " and not exists(select 1 from ac_table_ref t3 where t3.table_id=? and t3.fk_table=? and t3.fk_field=t1.name)" +
                " order by t1.name", param.getString("fkTable"),param.getString("tableId"),param.getString("fkTable"));

        return ResultT.success(array);
    }
}
